
/*
clang-12, -std=c99 -E -dI -dM 
#define __ORDER_BIG_ENDIAN__	4321
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_PDP_ENDIAN__ 	3412
#define __BYTE_ORDER__ 			__ORDER_LITTLE_ENDIAN__
*/

#ifndef __ENDIAN_H_
#define __ENDIAN_H_


#define BIG_ENDIAN 		__ORDER_BIG_ENDIAN__
#define LITTLE_ENDIAN 	__ORDER_LITTLE_ENDIAN__
#define PDP_ENDIAN 		__ORDER_PDP_ENDIAN__
#define BYTE_ORDER 		__BYTE_ORDER__

#include <stdint.h>

#define __bswap16(x) __builtin_bswap16(x)
#define __bswap32(x) __builtin_bswap32(x)
#define __bswap64(x) __builtin_bswap64(x)


#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__

// Definitions from musl libc
#define htobe16(x) __bswap16(x)
#define be16toh(x) __bswap16(x)
#define betoh16(x) __bswap16(x)
#define htobe32(x) __bswap32(x)
#define be32toh(x) __bswap32(x)
#define betoh32(x) __bswap32(x)
#define htobe64(x) __bswap64(x)
#define be64toh(x) __bswap64(x)
#define betoh64(x) __bswap64(x)
#define htole16(x) (uint16_t)(x)
#define le16toh(x) (uint16_t)(x)
#define letoh16(x) (uint16_t)(x)
#define htole32(x) (uint32_t)(x)
#define le32toh(x) (uint32_t)(x)
#define letoh32(x) (uint32_t)(x)
#define htole64(x) (uint64_t)(x)
#define le64toh(x) (uint64_t)(x)
#define letoh64(x) (uint64_t)(x)

// From Apple Open Source Libc
#define ntohs(x) __bswap16(x)
#define htons(x) __bswap16(x)
#define ntohl(x) __bswap32(x)
#define htonl(x) __bswap32(x)
#define ntohll(x) __bswap64(x)
#define htonll(x) __bswap64(x)
#define NTOHL(x) (x) = ntohl((uint32_t)x)
#define NTOHS(x) (x) = ntohs((uint16_t)x)
#define NTOHLL(x) (x) = ntohll((uint64_t)x)
#define HTONL(x) (x) = htonl((uint32_t)x)
#define HTONS(x) (x) = htons((uint16_t)x)
#define HTONLL(x) (x) = htonll((uint64_t)x)

#else // BIG_ENDIAN

// Definitions from musl libc
#define htobe16(x) (uint16_t)(x)
#define be16toh(x) (uint16_t)(x)
#define betoh16(x) (uint16_t)(x)
#define htobe32(x) (uint32_t)(x)
#define be32toh(x) (uint32_t)(x)
#define betoh32(x) (uint32_t)(x)
#define htobe64(x) (uint64_t)(x)
#define be64toh(x) (uint64_t)(x)
#define betoh64(x) (uint64_t)(x)
#define htole16(x) __bswap16(x)
#define le16toh(x) __bswap16(x)
#define letoh16(x) __bswap16(x)
#define htole32(x) __bswap32(x)
#define le32toh(x) __bswap32(x)
#define letoh32(x) __bswap32(x)
#define htole64(x) __bswap64(x)
#define le64toh(x) __bswap64(x)
#define letoh64(x) __bswap64(x)

// From Apple Open Source libc
#define ntohl(x) ((uint32_t)(x))
#define ntohs(x) ((uint16_t)(x))
#define htonl(x) ((uint32_t)(x))
#define htons(x) ((uint16_t)(x))
#define ntohll(x) ((uint64_t)(x))
#define htonll(x) ((uint64_t)(x))

#define NTOHL(x) (x)
#define NTOHS(x) (x)
#define NTOHLL(x) (x)
#define HTONL(x) (x)
#define HTONS(x) (x)
#define HTONLL(x) (x)

#endif // endian check

#endif //__ENDIAN_H_
